package util;

import org.apache.commons.io.FileUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.io.VelocityWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Map;

/**
 * 用一句话描述该文件作用
 *
 * @Author pengsamkee
 * create at 2016/11/11 9:21
 */
public class TemplateUtil {

    private static final Logger logger = LoggerFactory.getLogger(TemplateUtil.class);

    /**
     * 根据模板生成文件
     * @param templateMap
     * @param templateContent
     * @param file
     * @param encoding
     */
    public static void genFile(Map templateMap, String templateContent, File file, String encoding) {
        try {
            VelocityEngine velocityEngine = new VelocityEngine();
            velocityEngine.init();
            Context context = new VelocityContext(templateMap);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            VelocityWriter writer = new VelocityWriter(new VelocityWriter(new OutputStreamWriter(out, encoding), 4 * 1024, true));
            velocityEngine.evaluate(context, writer, "", templateContent);
            writer.flush();
            writer.close();

            FileUtils.writeByteArrayToFile(file, out.toByteArray());
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }

}
